package system

import (
	"bottle/global"
	"bottle/model/system"
	systemReq "bottle/model/system/request"
	systemRes "bottle/model/system/response"
	"bottle/utils"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	uuid "github.com/satori/go.uuid"
	"gorm.io/gorm"
)

type UserService struct{}

//const (
//	domain           = "developer.toutiao.com"
//	sandBoxDomain    = "open-sandbox.douyin.com"
//	code2SessionPath = "/api/apps/v2/jscode2session"
//)

func (UserService *UserService) Register(u system.User) (err error, userInter system.User) {
	var user system.User
	if !errors.Is(global.GVA_DB.Where("open_id = ?", u.OpenID).First(&user).Error, gorm.ErrRecordNotFound) { // 判断用户名是否注册
		return nil, user
	}

	// 否则 附加uuid 密码md5简单加密 注册
	//u.Password = utils.MD5V([]byte(u.Password))
	u.UUID = uuid.NewV4()
	err = global.GVA_DB.Create(&u).Error
	return err, u
}

func (UserService *UserService) Code2Session(ctx context.Context, req *systemReq.Code2SessionRequest) (*systemRes.Code2SessionResponseData, error) {
	domain := "api.weixin.qq.com"
	code2SessionPath := "/sns/jscode2session"
	reqDomain := domain
	reqBodyByte := fmt.Sprintf("?appid=%s&secret=%s&js_code=%s&grant_type=%s", req.AppId,req.Secret,req.JsCode,req.GrantType)
	respBody, err := utils.HttpGet(ctx, code2SessionPath, string(reqBodyByte), "http", reqDomain)
	resp := &systemRes.Code2SessionResponseData{}
	if err != nil {
		return nil, err
	}
	err = json.Unmarshal([]byte(respBody), resp)
	if err != nil {
		global.GVA_LOG.Error(respBody)
	}
	return resp, err
}

func (UserService *UserService) GetUserInfoByUUID (uuid string) (err error, user system.User) {
	err = global.GVA_DB.First(&user, "uuid=?", uuid).Error
	return err, user
}